package com.aaa.filter;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Resource
     private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取验证码
        String code = httpServletRequest.getParameter("code");


//        获取当前路径
        String path = httpServletRequest.getRequestURI();
//        如果不是loginapp/oauth/token直接跳出
        if (!path.contains("/oauth/token")) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        if (code == null) {
//            发送错误信息
            httpServletResponse.setContentType("application/json;charset=utf-8");
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            httpServletResponse.getWriter().write("{\"code\":\"400\",\"msg\":\"验证码不能为空\"}");
            return;
        }
        //通过key获取redis的缓存的正确验证码
        String redisCode = (String) redisTemplate.opsForValue().get("code");
        filterChain.doFilter(httpServletRequest, httpServletResponse);
        System.out.println("codeInRedis:" + redisCode);
        //如果匹配成功就放行
        if (code.equals(redisCode)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
        //否者就提示前端
        else {
            httpServletResponse.setContentType("application/json;charset=utf-8");
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            httpServletResponse.getWriter().write("{\"code\":\"400\",\"msg\":\"验证码错误\"}");
        }
    }
}
